<?php

namespace app\controller;

use app\controller\api\BaseController;
use Intervention\Image\ImageManagerStatic as Image;
use support\Request;

/**
 * Class UploadController
 * @package app\controller
 * @author ycr <Email: yuncran@126.com>
 */
class UploadController extends BaseController
{

    /**
     * 签名验证 -白名单
     * @var array
     */
    protected $signOptional = [];

    /**
     * 权限验证 -白名单
     * @var array
     */
    protected $authOptional = [];

    /**
     * 图片上传
     * @author ycr <Email: yuncran@126.com>
     */
    public function upload(Request $request)
    {
        $data = $this->base($request, '/upload/img/' . date('Ymd'));
        $realpath = $data['realpath'];

        try {
            $img = Image::make($realpath);
            $max_height = 1170;
            $max_width = 1170;
            $width = $img->width();
            $height = $img->height();
            $ratio = 1;
            if ($height > $max_height || $width > $max_width) {
                $ratio = $width > $height ? $max_width / $width : $max_height / $height;
            }
            $img->resize($width * $ratio, $height * $ratio)->save($realpath);
        } catch (\Exception $e) {
            unlink($realpath);
            return app('json')->fail('处理图片发生错误');
        }

        $data = ['url' => $data['url'], 'name' => $data['name'], 'size' => $data['size']];
        return app('json')->success('上传成功', $data);
    }


    /**
     * 上传头像
     * @param Request $request
     * @return \support\Response
     * @throws \Exception
     * @author ycr <Email: yuncran@126.com>
     */
    public function avatar(Request $request)
    {
        $file = current($request->file());

        if ($file && $file->isValid()) {
            $ext = strtolower($file->getUploadExtension());

            if (!in_array($ext, ['jpg', 'jpeg', 'gif', 'png'])) {
                return json(['code' => 2, 'msg' => '仅支持 jpg jpeg gif png格式']);
            }
            $image = Image::make($file);
            $width = $image->width();
            $height = $image->height();
            $size = min($width, $height);
            $relative_path = 'upload/avatar/' . date('Ym');
            $real_path = base_path() . "/public/api/$relative_path";
            if (!is_dir($real_path)) {
                mkdir($real_path, 0777, true);
            }
            $name = bin2hex(pack('Nn', time(), random_int(1, 65535)));
            $ext = $file->getUploadExtension();

            $image->crop($size, $size)->resize(300, 300);
            $path = base_path() . "/public/api/$relative_path/$name.lg.$ext";
            $image->save($path);

//            $image->resize(120, 120);
//            $path = base_path() . "/public/api/$relative_path/$name.md.$ext";
//            $image->save($path);

//            $image->resize(60, 60);
//            $path = base_path() . "/public/api/$relative_path/$name.$ext";
//            $image->save($path);

            $data = ['url' => "/public/api/$relative_path/$name.lg.$ext", 'name' => $name, 'size' => $size];
            return app('json')->success('上传成功', $data);

        }
        return app('json')->fail('file not found');
    }


    /**
     * 获取上传数据
     * @param Request $request
     * @param $relative_dir
     * @return array
     * @throws \Exception
     * @author ycr <Email: yuncran@126.com>
     */
    protected function base(Request $request, $relative_dir): array
    {
        $relative_dir = ltrim($relative_dir, '/');
        $file = current($request->file());
        if (!$file || !$file->isValid()) {
            return app('json')->fail('未找到上传文件');
        }

        $base_dir = base_path() . '/public/api/';
        $full_dir = $base_dir . $relative_dir;
        if (!is_dir($full_dir)) {
            mkdir($full_dir, 0777, true);
        }

        $ext = strtolower($file->getUploadExtension());
        $ext_forbidden_map = ['php', 'php3', 'php5', 'css', 'js', 'html', 'htm', 'asp', 'jsp'];
        if (in_array($ext, $ext_forbidden_map)) {
            return app('json')->fail('不支持该格式的文件上传');
        }

        $relative_path = $relative_dir . '/' . bin2hex(pack('Nn', time(), random_int(1, 65535))) . ".$ext";
        $full_path = $base_dir . $relative_path;
        $file_size = $file->getSize();
        $file_name = $file->getUploadName();
        $mime_type = $file->getUploadMimeType();
        $file->move($full_path);
        $image_with = $image_height = 0;
        if ($img_info = getimagesize($full_path)) {
            [$image_with, $image_height] = $img_info;
            $mime_type = $img_info['mime'];
        }
        return [
            'url' => "/public/api/$relative_path",
            'name' => $file_name,
            'realpath' => $full_path,
            'size' => $file_size,
            'mime_type' => $mime_type,
            'image_with' => $image_with,
            'image_height' => $image_height,
            'ext' => $ext,
        ];
    }


}